<template>
  <editor-layout
    submit-text="保存"
    @ok="handleOk"
    v-on="$listeners"
    v-loading="loading"
    element-loading-text="正在检测数据"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    :loading="saveLoading">
    <div class="upload-panel">
      <el-upload
        class="upload-demo"
        ref="upload"
        action=""
        accept=".xls,.xlsx"
        :on-change="handleFjChange"
        :before-upload="handleFjBeforeUpload"
        :show-file-list="false"
      >
        <el-button size="small" type="primary">选择文件</el-button>
      </el-upload>

      <div class="tip-line">
        <span class="red-text">红色</span>字体表示验证失败！黑色或空白表示数据正常
      </div>

      <div class="list-wrap">
        <el-table
          v-show="columns.length > 0"
          :data="tableData"
          height="100%"
          border
          stripe
          size="mini"
          style="width: 100%">
          <el-table-column type="index" width="50" />

          <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :property="item.prop">
            <template slot-scope="{row}">
              <!-- 验证失败的数据 -->
              <div v-if="row['_' + item.prop]" class="red-text">
                <el-tooltip :content="row['_' + item.prop]" placement="bottom" effect="light">
                  <span>{{row[item.prop] || '空'}}</span>
                </el-tooltip>
              </div>
              <div v-else>
                {{row[item.prop]}}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

  </editor-layout>
</template>

<script>
import {toTable} from '@/utils/Excel'
import {checkBankCard, checkTax, isMobile, isEmail} from '@/utils/validate'
import {postSysTuserCheckPhones, postSysTuserBatch} from '$my/code/api/t-user'

const SexArr = ['女', '男', '未知']
function checkSex(str) {
  return SexArr.includes(str)
}

export default {
  name: 'upload-panel',
  data() {
    return {
      loading: false,
      saveLoading: false,
      tableData: [],
      columns: [],
      mapper: {
        姓名: 'username',
        手机号: 'mobile',
        邮箱: 'email',
        性别: 'sex',
        信用代码: 'billing',
        地址: 'address',
        开户行: 'bank',
        银行卡号: 'bankCard'
      },
      hasError: false
    }
  },
  methods: {
    handleFjBeforeUpload() {
      return false
    },
    handleFjChange(file) {
      this.loading = true
      this.hasError = false

      toTable(file, this.mapper).then(async (res) => {
        const list = res.dataList
        this.checkData(list)

        const mobiles = list.map(o => o.mobile)
        const phones = await postSysTuserCheckPhones(mobiles)
        phones.forEach(phone => {
          // 已经存在的该数据
          if(phone.exist) {
            const finded = list.find(item => item.mobile === phone.num)
            finded._mobile = '该手机号用户已存在！'
            this.hasError = true
          }
        })

        this.columns = res.columns
        this.tableData = list

        this.loading = false
      })
    },
    checkData(list) {
      let hasError = false
      list.forEach(item => {
        if(!this.validateRule(item, 'bankCard', checkBankCard, '银行卡号格式不正确')) {
          hasError = true
        }
        if(!this.validateRule(item, 'billing', checkTax, '信用代码格式不正确')) {
          hasError = true
        }
        if(!this.validateRule(item, 'mobile', isMobile, '手机号码格式不正确')) {
          hasError = true
        }
        if(!this.validateRule(item, 'email', isEmail, '邮箱格式不正确')) {
          hasError = true
        }
        if(!this.validateRule(item, 'sex', checkSex, '性别必须为：女/男/未知 之一')) {
          hasError = true
        }

        if(!item.mobile || item.mobile.length === 0) {
          item._mobile = '手机号不能为空'
          hasError = true
        }
      })

      this.hasError = hasError
    },
    validateRule(item, key, validate, msg) {
      if(!item[key]) return true
      if(!validate(item[key])) {
        item['_' + key] = msg
        return false
      }
      return true
    },

    handleOk() {
      console.info(this.hasError)
      console.info(this.tableData)
      if(this.hasError) {
        this.$alert('红色数据格式不正确，请修复后重新上传', '警告', {
          confirmButtonText: '关闭',
          type: 'warning'
        }).then(() => {})
      } else {
        this.saveLoading = true
        postSysTuserBatch(this.tableData).then(res => {
          this.saveLoading = false
          this.$notify.success('保存成功！')
          this.$emit('on-ok')
        }).catch(e => {
          this.saveLoading = false
          console.error(e)
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-panel {
  height: 100%;
  display: flex;
  flex-direction: column;

  .list-wrap {
    flex: 1;
    width: 100%;
    margin-top: 10px;
    border: 1px dotted #1890ff;
    overflow-y: scroll;
  }

  .red-text {
    color: #f74e57;
  }
}
</style>
